package com.example.stuwork.service.impl;

import com.example.stuwork.common.Result;
import com.example.stuwork.dao.QuizDao;
import com.example.stuwork.dao.QuizQuestionDao;
import com.example.stuwork.dao.QuizSubmissionDao;
import com.example.stuwork.pojo.Quiz;
import com.example.stuwork.pojo.QuizQuestion;
import com.example.stuwork.pojo.QuizSubmission;
import com.example.stuwork.service.QuizSubmissionService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试提交服务实现类
 */
@Service
public class QuizSubmissionServiceImpl implements QuizSubmissionService {

    @Autowired
    private QuizSubmissionDao quizSubmissionDao;
    
    @Autowired
    private QuizDao quizDao;
    
    @Autowired
    private QuizQuestionDao quizQuestionDao;
    
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public Result<?> submitQuiz(QuizSubmission submission) {
        try {
            // 1. 检查测试状态
            Quiz quiz = quizDao.getById(submission.getQuizId());
            if (quiz == null) {
                return Result.error("测试不存在");
            }
            
            if (quiz.getStatus() != 1) {
                return Result.error("测试未开始或已结束，无法提交");
            }
            
            // 2. 检查是否已经提交过
            boolean isSubmitted = quizSubmissionDao.isSubmitted(submission.getQuizId(), submission.getStudentId());
            if (isSubmitted) {
                return Result.error("您已经提交过该测试，不能重复提交");
            }
            
            // 3. 插入提交记录
            int result = quizSubmissionDao.insert(submission);
            if (result <= 0) {
                return Result.error("提交测试答案失败");
            }
            
            // 4. 如果没有提供分数，则计算得分
            if (submission.getScore() == null || submission.getScore() == 0) {
                quizSubmissionDao.calculateScore(submission.getSubmissionId());
            }
            
            // 5. 查询得分并返回
            QuizSubmission updatedSubmission = quizSubmissionDao.getById(submission.getSubmissionId());
            
            return Result.success("提交成功", updatedSubmission);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("提交测试答案失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<QuizSubmission>> getSubmissionsByQuizId(Long quizId) {
        try {
            List<QuizSubmission> submissions = quizSubmissionDao.findByQuizId(quizId);
            return Result.success(submissions);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测试提交列表失败");
        }
    }

    @Override
    public Result<List<QuizSubmission>> getSubmissionsByStudentId(String studentId) {
        try {
            List<QuizSubmission> submissions = quizSubmissionDao.findByStudentId(studentId);
            return Result.success(submissions);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取学生提交记录失败");
        }
    }

    @Override
    public Result<QuizSubmission> getStudentSubmission(Long quizId, String studentId) {
        try {
            QuizSubmission submission = quizSubmissionDao.findByQuizIdAndStudentId(quizId, studentId);
            if (submission == null) {
                return Result.error("未找到提交记录");
            }
            
            // 解析答案JSON字符串
            try {
                Map<String, String> answerMap = objectMapper.readValue(submission.getAnswers(), 
                        new TypeReference<Map<String, String>>() {});
                submission.setAnswerMap(answerMap);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            
            // 获取测试题目
            List<QuizQuestion> questions = quizQuestionDao.findByQuizId(quizId);
            
            // 创建包含题目和学生答案的结果
            Map<String, Object> result = new HashMap<>();
            result.put("submission", submission);
            result.put("questions", questions);
            
            return Result.success(submission);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取学生提交记录失败");
        }
    }

    @Override
    public Result<?> calculateScore(Long submissionId) {
        try {
            int result = quizSubmissionDao.calculateScore(submissionId);
            if (result > 0) {
                // 获取更新后的提交记录
                QuizSubmission submission = quizSubmissionDao.getById(submissionId);
                return Result.success("计算得分成功", submission);
            } else {
                return Result.error("计算得分失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("计算得分失败");
        }
    }

    @Override
    public Result<Map<String, Object>> getQuizStats(Long quizId) {
        try {
            Map<String, Object> stats = quizSubmissionDao.getQuizSubmissionStats(quizId);
            if (stats == null) {
                stats = new HashMap<>();
                stats.put("submission_count", 0);
                stats.put("average_score", 0);
                stats.put("highest_score", 0);
                stats.put("lowest_score", 0);
            }
            return Result.success(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测试统计信息失败");
        }
    }

    @Override
    public Result<Boolean> isSubmitted(Long quizId, String studentId) {
        try {
            boolean submitted = quizSubmissionDao.isSubmitted(quizId, studentId);
            return Result.success(submitted);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查提交状态失败");
        }
    }
} 